<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: 当燃 2016-01-09
 */
namespace app\admin\controller;
use app\admin\logic\GoodsLogic;
use app\admin\logic\OrderLogic;
use think\AjaxPage;
use think\Page;
use think\Db;

header("Content-Type: text/html; charset=utf8");
class Exchange extends Base {
	
	/*
    * 初始化操作
    */
    public function _initialize()
    {
        parent::_initialize();
        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where("user_id", $user['user_id'])->find();
            session('user', $user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
        }
    }    

    public function index(){
    
        return $this->fetch();
    }
    
    /*
     * 兑换产品管理
     * */
    public function goodsManage(){
    	$lists = M('exchange_goods')->order("goods_id desc")->select();
    	//print_r($lists);
    	if($lists){
    		
    	}
    	$page = empty(I("post.p"))?1:I("post.p");
        $count = M('exchange_goods')->count();
        $Page  = new AjaxPage($count,10);
        $this->assign('pager',$Page->show());
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
       
    
    public function addeditGoods(){
    	
    	if(I('is_ajax') == 1 && IS_POST){
    		$data = I('post.');//收集数据
    		if($data){
    			if(empty($data['goods_name'])){
    				echo json_encode(array('status'=>-1,'msg'=>'商品名称不能为空'));
    				exit;
    			}
    			if(empty($data['exchange_integral']) || is_int($data['exchange_integral'])){
    				echo json_encode(array('status'=>-1,'msg'=>'兑换积分不能为空,并且必须是数字'));
    			    exit;
    			}
    		}
    		if($data['goods_id']){
    			$goods_id = $data['goods_id'];
    		}
    		//处理商品图片
    		$data['goods_images'] = array_filter($data['goods_images']);
    		$data['goods_images'] = $data['goods_images'] ? json_encode($data['goods_images']) : '';
    		//处理物流配送区
    		$data['shipping_area_ids'] = implode(',',I('shipping_area_ids/a',[]));
            $data['shipping_area_ids'] = $data['shipping_area_ids'] ? $data['shipping_area_ids'] : '';
    	    $data['on_time'] = time();
    	    if($goods_id){
    	    	$data['last_update'] = time();
    	    	unset($data['goods_id']);
    	    	$r = M('exchange_goods')->where(array('goods_id'=>$goods_id))->save($data);
    	    }
    	    else{
    	    	$repeat_name = M('exchange_goods')->where(array('goods_name'=>$data['goods_name']))->find();
			    if($repeat_name){
			    	echo json_encode(array('status'=>-1,'msg'=>'商品名称重复，似乎该商品已存在！'));
				    exit;
			    }
    	        $r = M('exchange_goods')->add($data);	
    	    }
    	    if($r){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('admin/Exchange/goodsManage')),
                );
                $this->ajaxReturn($return_arr);
    	    }else{
    	    	$return_arr = array(
                    'status' => -1,
                    'msg' => '操作失败',
                    'data' => array('url' => U('admin/Exchange/goodsManage')),
                );
                $this->ajaxReturn($return_arr);
    	    }
    	}
    	$goods_id = I('goods_id/d');
    	if($goods_id){
    		$goodsInfo = M('exchange_goods')->where(array('goods_id'=>$goods_id))->find();
    	    if(!$goodsInfo){
    	    	$this->error('该商品不存在！');
    	    }
    	}
    	$suppliersList = M("suppliers")->select();
        $plugin_shipping = M('plugin')->where(array('type'=>array('eq','shipping')))->select();//插件物流
        $shipping_areas = M('shipping_area')->where('1=1')->select();
        foreach($shipping_areas as $key => $val){
            $shipping_areas[$key]['config'] = unserialize($shipping_areas[$key]['config']);
        }
        $shipping_area = $shipping_areas;//配送区域
        $goods_shipping_area_ids = explode(',',$goodsInfo['shipping_area_ids']);
        $this->assign('goods_shipping_area_ids',$goods_shipping_area_ids);
        $this->assign('shipping_area',$shipping_area);
        $this->assign('plugin_shipping',$plugin_shipping);
        $this->assign('suppliersList',$suppliersList);
        if($goodsInfo['goods_images']){
           $goodsImages = json_decode($goodsInfo['goods_images'],true);	
           $this->assign('goodsImages', $goodsImages);  // 商品相册
        }
        $cateList = M('exchange_category')->select();
        $this->assign('categoryList',$cateList);
        $this->assign('goodsInfo', $goodsInfo);
    	return $this->fetch();
    }
    
    //删除商品
    public function delGoods(){
    	$goods_id = I('goods_id/d');
    	//是否存在订单
    	$is_order = M('exchange_record')->where(array('goods_id'=>$goods_id))->select();
    	if($is_order){
    		$return_arr = array(
                'status' => -1,
                'msg' => '该产品存在订单，不能删除！',
                'data' => array('url' => U('admin/Exchange/goodsManage')),
            );
            $this->ajaxReturn($return_arr);
    	}
    	$r = M('exchange_goods')->where(array('goods_id'=>$goods_id))->delete();
		if(IS_POST){
		    if($r){
				$return_arr = array(
	                'status' => 1,
	                'msg' => '操作成功',
	                'data' => array('url' => U('admin/Exchange/goodsManage')),
	            );
	            $this->ajaxReturn($return_arr);
			}
			else{
				$return_arr = array(
	                'status' => -1,
	                'msg' => '删除失败',
	                'data' => array('url' => U('admin/Exchange/goodsManage')),
	            );
	            $this->ajaxReturn($return_arr);
			}	
		}else{
			if($r){
				$this->success('删除成功！');
			}else{
				$this->error('删除失败！');
			}
		}
    }
    
    //分类管理
    public function category(){
    	$cateList = M('exchange_category')->select();
    	foreach($cateList as $key=>$val){
    		$count = M('exchange_goods')->where(array('cat_id'=>$id))->count(1);
    		$cateList[$key]['g_num'] = $count; 
    	}
    	$page = empty(I("post.p"))?1:I("post.p");
        $count = M('exchange_category')->count();
        $Page  = new AjaxPage($count,10);
        $this->assign('pager',$Page->show());
    	$this->assign('categoryList',$cateList);
    	return $this->fetch();
    }
    
    //编辑添加分类
    public function addeditCategory(){
    	
    	if(I('is_ajax') == 1 && IS_POST){
    		$data = I('post.');
    		if(empty($data['title'])){
    			$return_arr = array(
	                'status' => -1,
	                'msg' => '分类名称不能为空',
	                'data' => array(),
	            );
	            $this->ajaxReturn($return_arr);
    		}
    		$data['addtime'] = time();
    		if($data['id']){
    			$id = $data['id'];
    			unset($data['id']);
    			$r = M('exchange_category')->where(array('id'=>$id))->save($data);
    		}else{
    		    $r = M('exchange_category')->add($data);	
    		}
    		
    		if($r){
    			$return_arr = array(
	                'status' => 1,
	                'msg' => '操作成功！',
	                'data' => array('url' => U('admin/Exchange/category')),
	            );
	            $this->ajaxReturn($return_arr);
    		}
    		else{
    			$return_arr = array(
	                'status' => -1,
	                'msg' => '操作失败！',
	                'data' => array(),
	            );
	            $this->ajaxReturn($return_arr);
    		}
    	}
    	$id = I('id/d');
    	$cate = M('exchange_category')->where(array('id'=>$id))->find(); 
    	$this->assign('cate',$cate);
    	return $this->fetch();
    } 
    
    
    //删除分类
    public function delCategory(){
    	$id = I('id/d');
    	//是否存在订单
    	$is_g = M('exchange_goods')->where(array('cat_id'=>$id))->select();
    	if($is_g){
    		$return_arr = array(
                'status' => -1,
                'msg' => '该分类存在商品，不能删除！',
                'data' => array('url' => U('admin/Exchange/category')),
            );
            $this->ajaxReturn($return_arr);
    	}
    	$r = M('exchange_category')->where(array('id'=>$id))->delete();
		if(IS_POST){
		    if($r){
				$return_arr = array(
	                'status' => 1,
	                'msg' => '操作成功',
	                'data' => array('url' => U('admin/Exchange/category')),
	            );
	            $this->ajaxReturn($return_arr);
			}
			else{
				$return_arr = array(
	                'status' => -1,
	                'msg' => '删除失败',
	                'data' => array('url' => U('admin/Exchange/category')),
	            );
	            $this->ajaxReturn($return_arr);
			}	
		}else{
			if($r){
				$this->success('删除成功！');
			}else{
				$this->error('删除失败！');
			}
		}
    }
    
    
    
    
    /*
     * 兑换记录管理
     * */
    public function exchangeRecord(){
    	$lists = M('exchange_record')->select();
    	foreach($lists as $key=>$val){
    	    $user = M('users')->where(array('user_id'=>$val['user_id']))->find();
    	    $lists[$key]['user'] = $user; 	
    	}
    	$order_status = array('未确认','已确认','已完成');
    	$pay_status = array('未支付','已支付');
    	$shipping_status = array('未发货','已发货');
    	$this->assign('order_status',$order_status);
    	$this->assign('pay_status',$pay_status);
    	$this->assign('shipping_status',$shipping_status);
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    
    
    /*
     * 兑换详情
     * */
    public function recordInfo(){
    	$id = I('id/d');
    	$recinfo = M('exchange_record')->where('id',$id)->find();
    	$user = M('users')->where(array('user_id'=>$this->user_id))->find();
    	$recinfo['user'] = $user;
    	$address = M("user_address")->where("address_id",$recinfo['address_id'])->find();
    	if(!$address){//如果地址为空则取默认地址
    		$address = M('user_address')->where(array('user_id'=>$this->user_id,'is_default'=>1))->find(); 
    		$orderLogic = new OrderLogic();   
    		$add2 = $orderLogic->getAddressName($address['province'],$address['city'],$address['district']); 
    	    $address['address'] = $add2.$address['address'];
    	}
    	$recinfo['address'] = $address;
    	
    	$action_log = json_decode($recinfo['order_action'],true);
    	if(is_array($action_log)){
    	foreach($action_log as $key=>$val){
        	$action_user = M('users')->where('user_id',$val['action_user'])->find();
        	$action_log[$key]['action_user_name'] = $action_user['nickname'];
        }
        }
        $recinfo['order_action'] = $action_log;
        if($recinfo['order_status'] == 0 && $recinfo['pay_status'] == 1){
            $button['sure'] = '确认订单'; 
        }	
        if($recinfo['order_status'] == 1 && $recinfo['pay_status'] == 1 && $recinfo['shipping_status'] == 0){
            $button['delivery'] = '去发货'; 
        }
        if($recinfo['order_status'] == 1 && $recinfo['pay_status'] == 1 && $recinfo['shipping_status'] == 1){
            $button['delivery_cancel'] = '取消发货'; 
        }
        $button['invalid'] = '无效';

        $this->assign('button',$button);
    	$good = M('exchange_goods')->where('goods_id',$recinfo['goods_id'])->find();
    	
    	if($recinfo['shipping_info']){
    		$recinfo['shipping_info'] = json_decode($recinfo['shipping_info'],true);
    	    $recinfo['shipping_info']['shipping_name'] = M('plugin')->where('code',$recinfo['shipping_info']['shipping_code'])->getField('name');
    	}else{
    		$recinfo['shipping_info']=array(
	    		       'shipping_code' => '',
	    		       'invoice_no' => '' 
    		);
    	}
    	
    	$order_status = array('未确认','已确认','已完成');
    	$pay_status = array('未支付','已支付');
    	$shipping_status = array('未发货','已发货');
    	$this->assign('order_status',$order_status);
    	$this->assign('pay_status',$pay_status);
    	$this->assign('shipping_status',$shipping_status);
    	
    	$this->assign('good',$good);
    	$this->assign('order',$recinfo);
    	return $this->fetch();
    }
    
    
    /*
     * 兑换商品操作日志
     */
    public function exchange_record_action(){
    	
    	$id = I('id/d');
    	$type = I('type');
    	$action_note = I('note');
    	if($id && $type){
	    	$res = exchange_order_action($type,$id,$action_note);
	    	if($res !== false && $a !== false){
	            if($action == 'remove') {
	                exit(json_encode(array('status' => 1, 'msg' => '操作成功', 'data' => array('url' => U('admin/order/index')))));
	            }
	    	 	exit(json_encode(array('status' => 1,'msg' => '操作成功')));
	    	}else{
	            if($action == 'remove') {
	                exit(json_encode(array('status' => 0, 'msg' => '操作失败', 'data' => array('url' => U('admin/order/index')))));
	            }
	    	 	exit(json_encode(array('status' => 0,'msg' => '操作失败')));
	    	}
    	}
    	else{
    		$this->error('参数错误',U('Admin/Exchange/recordInfo',array('id'=>$id)));
    	}

    }
    
    
    /**
     *  兑换专区发货页面
     */
    public function exchangeDelivery(){
    	
    	if(IS_POST){
    		
    		$id = I('post.id');
    		$action_note = I('post.note');
    		$invoice_no = I('post.invoice_no');
    		$shipping_code = I('post.shipping_code');
    		
    		$data = I("post.");

    		if($invoice_no && $shipping_code){
    			$shipping_info = array('invoice_no'=>$invoice_no,'shipping_code'=>$shipping_code);
    			$r = M('exchange_record')->where('id',$id)->save(array('shipping_info'=>json_encode($shipping_info)));
    		}
    		else{
    			$this->success('配送方式或者物流单号不能为空',U('Admin/Exchange/exchangeDelivery',array('id'=>$id)));
    		}
    		$action = 'delivery';
    		$msg = exchange_order_action($action,$id,$action_note);
    	    if($r && $msg){
				$this->success('操作成功',U('Admin/Exchange/recordInfo',array('id'=>$id)));
			}else{
				$this->success('操作失败',U('Admin/Exchange/exchangeDelivery',array('id'=>$id)));
			}
    	}else{
    		$id = I('get.id');
	    	$model = M('exchange_record');
	        $order = $model->where('id',$id)->find();
	    	$user = M("users")->where('user_id',$order['user_id'])->find();
	    	$order['user'] = $user; 
	    	$address = M("user_address")->where("address_id",$order['address_id'])->find();
	    	if(!$address){//如果地址为空则取默认地址
	    		$address = M('user_address')->where(array('user_id'=>$this->user_id,'is_default'=>1))->find(); 
	    		$orderLogic = new OrderLogic();   
	    		$add2 = $orderLogic->getAddressName($address['province'],$address['city'],$address['district']); 
	    	    $address['address'] = $add2.$address['address'];
	    	}
	    	$order['address'] = $address;
	    	$good = M('exchange_goods')->where('goods_id',$order['goods_id'])->find();
	    	$order['good'] = $good;
	    	$order['shipping_info'] = json_decode($order['shipping_info'],true);	
	    	
	    	//$shipping = M('shipping')->select();
            $shipping = M('plugin')->where(array('type'=>'shipping','status'=>1))->select();
            $this->assign('shipping',$shipping);
	        $this->assign('order',$order);
	        return $this->fetch();
    	}
    }
}